<script setup name="stafflist">
import OAMain from '@/components/OAMain.vue';
import { ref, reactive, onMounted, watch, onErrorCaptured } from "vue";
import timeFormatter from '@/utils/timeFormatter';
import staffHttp from '@/api/staffHttp';
import { ElMessage } from 'element-plus';
import OADialog from '@/components/OADialog.vue';
import { useAuthStore } from '@/stores/auth';

let staffs = ref([])
let authStore = useAuthStore()
let pagination = reactive({
    total: 0,
    page: 1
})

let page_size = ref(10)
let handleIndex = 0

async function fetchStaffList(page, page_size) {
    try {
        // 获取员工列表
        let data = await staffHttp.getStaffList(page, page_size, filterForm)
        pagination.total = data.count
        staffs.value = data.results
        pagination.page = page
    } catch (detail) {
        ElMessage.error(detail)
    }
}

onMounted(async () => {
    await fetchStaffList(1, page_size.value)
    try {
        let data = await staffHttp.getAllDepartment()
        departments.value = data.results;
    } catch (detail) {
        ElMessage.error('')
    }
})

watch(() => pagination.page, async function (value) {
    await fetchStaffList(value, page_size.value)
})

watch(page_size, async function (value) {
    pagination.page = 1
    await fetchStaffList(pagination.page, value)
})

const onSubmitEditStaff = async () => {
    try {
        let staff = staffs.value[handleIndex]
        let newstaff = await staffHttp.updateStaffStatus(staff.uid, staffForm.status)
        ElMessage.success('员工状态更新成功')
        staffs.value.splice(handleIndex, 1, newstaff)
    } catch (detail) {
        ElMessage.error('员工状态更新失败')
    }
    dialogVisible.value = false
}

let dialogVisible = ref(false)
let staffForm = reactive({
    status: 1,
})

const onEditStaff = (index) => {
    handleIndex = index
    dialogVisible.value = true;
    let staff = staffs.value[handleIndex]
    // 默认在当前员工的状态上停留
    staffForm.status = staff.status
}
let departments = ref([])
let filterForm = reactive({
    department_id: null,
    realname: '',
    data_joined: []
})

let tableRef = ref()
const onSearch = async () => {
    await fetchStaffList(1, page_size.value)
}

const onDowload = async () => {
    let rows = tableRef.value.getSelectionRows()
    if(!rows || rows.length==0){
        ElMessage.info("请先选择要导出的员工")
        return
    }
    try{
        let response = await staffHttp.downloadStaffs(rows.map(row => row.uid))
        // 借助a标签，将response数据放到a标签的ref属性上，然后模拟点击行为
        // 将返回的二进制数据创建成一个url对象
        let href = URL.createObjectURL(response.data)
        // 创建a标签
        const a = document.createElement('a')
        a.href = href
        // 设置a标签的download属性,点击后才会执行下载操作
        a.setAttribute('download', '员工信息.xlsx')
        document.body.appendChild(a)
        // 模拟点击行为，浏览器启动下载操作（下载href指定的数据）
        a.click()
        // 执行结束，移除a标签
        document.body.removeChild(a)
        // 移除URL数据
        URL.revokeObjectURL(href)
    }catch(detail){
        ElMessage.error(detail)
    }
}


const onUploadSuccess = () => {
    ElMessage.success("员工信息上传成功")
    // 重写获取第一页
    fetchStaffList(1, page_size.value)
}
const onUploadFail = (error) => {
    console.log(error)
    const detail = JSON.parse(error.message).detail
    ElMessage.error(detail)
}


const BASE_URL = import.meta.env.VITE_BASE_URL
</script>

<template>
    <OADialog title="修改员工状态" v-model="dialogVisible" @submit="onSubmitEditStaff">
        <el-form :model="staffForm" label-width="100px">
            <el-form-item label="状态">
                <el-radio-group v-model="staffForm.status">
                    <el-radio :value="1">激活</el-radio>
                    <el-radio :value="3">锁定</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </OADialog>
    <OAMain title="员工列表">
        <el-card>
            <el-form :inline="true" class="my-inline-form">
                <el-form-item label="按部门">
                    <el-select v-model="filterForm.department_id">
                        <el-option v-for="department in departments" :label="department.name" :value="department.id"
                            :key="department.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="按姓名">
                    <el-input v-model="filterForm.realname"></el-input>
                </el-form-item>
                <el-form-item label="按入职时间">
                    <el-date-picker v-model="filterForm.data_joined" type="daterange" unlink-panels range-separator="到"
                        start-placeholder="起始日期" end-placeholder="截至日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="搜索">
                    <el-button type="primary" icon="Search" @click="onSearch"></el-button>
                </el-form-item>
                <el-form-item label="批量下载">
                    <el-button type="danger" icon="Download" @click="onDowload"></el-button>
                </el-form-item>
                <el-form-item label="批量导入">
                    <el-upload 
                        :action="BASE_URL + '/staff/upload'"
                        accept=".xlsx, .xls"
                        :auto-upload="true"
                        :show-file-list="false"
                        :on-success="onUploadSuccess"
                        :on-error="onUploadFail"
                        :headers="{Authorization: `jwt ${authStore.token}`}">
                        <el-button type="danger" icon="Upload"></el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card>
            <el-table :data="staffs" ref="tableRef">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="60">
                    <template #default="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="realname" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column label="入职时间">
                    <template #default="scope">
                        {{ timeFormatter.stringFromDate(scope.row.date_joined) }}
                    </template>
                </el-table-column>
                <el-table-column prop="department.name" label="部门"></el-table-column>
                <el-table-column label="状态">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
                        <el-tag v-else-if="scope.row.status == 2" type="warning">未激活</el-tag>
                        <el-tag v-else type="danger">已锁定</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" icon="Edit" circle @click="onEditStaff(scope.$index)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <div style="display: flex; justify-content: space-between;">
                    <el-form-item label="每页：">
                        <el-select v-model="page_size" size="small" style="width: 100px;">
                            <el-option select label="10条/页" :value="10" />
                            <el-option label="20条/页" :value="20" />
                        </el-select>
                    </el-form-item>
                    <el-pagination background layout="prev, pager, next" :total="pagination.total"
                        v-model:currentPage="pagination.page" :page-size="page_size" />
                </div>
            </template>
        </el-card>
    </OAMain>
</template>
<style>
.my-inline-form .el-input {
    --el-input-width: 104px;
}

.my-inline-form .el-select {
    --el-select-width: 104px;
}

.my-form-form .el-form-item {
    margin-right: 20px;
}
</style>